package matthias.WagoApp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.net.URL;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;


public class WagoAppActivity extends TabActivity {
	
	public static final String LOG_TAG="WAGOAPP";
	public static final int MENU_LANGUAGE = 100;
	public static final int MENU_LANGUAGE_DE = 101;
	public static final int MENU_LANGUAGE_IT = 102;
	public static final int MENU_LANGUAGE_EN = 103;
	public static final int MENU_SETTINGS = 200;
	public static final int MENU_EXIT = 300;
	
	public  String ip="1"; // IP Address of Controllers
	public boolean	en_sim=true;
    
	public static Locale locale ;
	
    /** Called when the activity is first created. */
    static final String[] ListINPUT = new String[] { // Here are the names of inputs entering! Respect the addresses have to agree!
    	"E0.0","E0.1","E0.2","E0.3","E0.4","E0.5","E0.6","E0.7","E1.0","E1.1","E1.2","E1.3","E1.4"
      };
    static final String[] ListOUTPUT = new String[] { // Enter here the name of exits! Please note that the addresses of the flags must agree!
        "A0.0","A0.1","A0.2","A0.3","A0.4","A0.5","A0.6","A0.7","A1.0","A1.1","A1.2","A1.3","A1.4","A1.5"
        ,"A1.6","A1.7","A2.0","A2.1","A2.2","A2.3","A2.4"
      };
    
    final static int maxAnzahlIO = 25; // Either size of list input or output list when bigger
    
    private int[] ArrayInputs = new int[ListINPUT.length];
	private int[] ArrayOutputs = new int[ListOUTPUT.length];
	private int[] ArrayMerker = new int[ListOUTPUT.length];
	
	private ListView ListeOutput=null;
	private ListView ListeInput=null;
	EditText mEditText_Merker1=null;
	EditText mEditText_Merker2=null;
	EditText mEditText_Merker3=null;
	TextView textview_Merker1=null;
	TextView textview_Merker2=null;
	TextView textview_Merker3=null;
	
	
	@Override
    public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        try{
        	loadSettings();
        }catch (Exception e) {
        	Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
		}     
        
        mEditText_Merker1=(EditText)findViewById(R.id.editText1);
        mEditText_Merker2=(EditText)findViewById(R.id.editText2);
        mEditText_Merker3=(EditText)findViewById(R.id.editText3);
        textview_Merker1=(TextView)findViewById(R.id.textViewMerker1);
        textview_Merker2=(TextView)findViewById(R.id.textViewMerker2);
        textview_Merker3=(TextView)findViewById(R.id.textViewMerker3);
        
        TabHost mTabHost = getTabHost();
       
        ListeInput=(ListView)findViewById(R.id.INPUTS);
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, ListINPUT);
        ListeInput.setAdapter(adapter1);
       
        //ListeInput.setEnabled(false); // Inputs can not be clicked
        ListeInput.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
        ListeInput.setClickable(false);
        ListeInput.setItemsCanFocus(false);
        ListeInput.setPressed(false);
        ListeInput.setSelected(false);
        ListeInput.setOnItemClickListener(onListClick); // Inputs can not be clicked
        
        ListeOutput=(ListView)findViewById(R.id.OUTPUTS);
        ArrayAdapter<String> adapter11 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, ListOUTPUT);
        ListeOutput.setAdapter(adapter11);
        ListeOutput.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
        ListeOutput.setClickable(false);
        ListeOutput.setOnItemClickListener(onListClick);
        
        mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator(getString(R.string.Input_name)).setContent(R.id.INPUTS));
        mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator(getString(R.string.Output_name)).setContent(R.id.OUTPUTS));
        mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator(getString(R.string.Merker_name)).setContent(R.id.layout_tab_3));
       
        mTabHost.setCurrentTab(0); //which is the front tab

        selector();

        final Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	try{
            			if (mEditText_Merker1.length()!= 0){
            				URL page = new URL(ip+"/WRITEPI?ADR1=MD100&VALUE1="+mEditText_Merker1.getText()+"&FORMAT1=%d");
            				page.getContent();
            				mEditText_Merker1.setText("");
            			}
            			if (mEditText_Merker2.length()!= 0){
            				URL page = new URL(ip+"/WRITEPI?ADR1=MD101&VALUE1="+mEditText_Merker2.getText()+"&FORMAT1=%d");
            				page.getContent();
            				mEditText_Merker2.setText("");
            			}
            			if (mEditText_Merker3.length()!= 0){
            				URL page = new URL(ip+"/WRITEPI?ADR1=MD102&VALUE1="+mEditText_Merker3.getText()+"&FORMAT1=%d");
            				page.getContent();
            				mEditText_Merker3.setText("");
            			}
					}catch (Exception e){System.out.println (getString(R.string.Error1_name));}
				selector();
            }
        }); 
        
        if (!en_sim){
        	// don't execute this in simulation mode
        	checkip();
        	new SynchTask().execute();
        }else{
        	Toast.makeText(getBaseContext(),getString(R.string.app_simulation_on),Toast.LENGTH_LONG).show();
        }
        	
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent i) {
	    super.onActivityResult(requestCode, resultCode, i);
	    if(resultCode==RESULT_OK && (requestCode==1 || requestCode==2)){
	    	
	    	ip = i.getStringExtra("ip");
	    	if (i.getStringExtra("en_sim").compareTo("true")==0){
		    	en_sim=true;
		    }else{
		    	en_sim=false;
			}
		}else{
	    	
	    }
	    	
	}

	
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		
		SubMenu langMenu = menu.addSubMenu(0, MENU_LANGUAGE, 2, getString(R.string.app_language)).setIcon(android.R.drawable.ic_menu_mapmode);
			langMenu.add(1, MENU_LANGUAGE_DE, 0, getResources().getStringArray(R.array.languages_array)[0]);
			langMenu.add(1, MENU_LANGUAGE_IT, 0, getResources().getStringArray(R.array.languages_array)[1]);
			langMenu.add(1, MENU_LANGUAGE_EN, 0, getResources().getStringArray(R.array.languages_array)[2]);
		SubMenu settingsMenu = menu.addSubMenu(0, MENU_SETTINGS, 2, getString(R.string.app_settings)).setIcon(android.R.drawable.ic_menu_preferences);
		SubMenu quitMenu = menu.addSubMenu(0, MENU_EXIT, 2, getString(R.string.app_close)).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
			
        return super.onCreateOptionsMenu(menu);
    }
	
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()){

        case MENU_LANGUAGE_DE:
            locale = new Locale("de"); 
            changeLanguage();
            break;

        case MENU_LANGUAGE_IT:
        	locale = new Locale("it"); 
        	changeLanguage();
            break;  

        case MENU_LANGUAGE_EN:
        	locale = new Locale("en");
        	changeLanguage();
            break;  
            
        case MENU_SETTINGS:
        	try {
        		Intent i = new Intent(WagoAppActivity.this, settings_project.class);
        		i.putExtra("ip", ip);
        		i.putExtra("en_sim", ""+en_sim);
        		startActivityForResult(i,1);
        	}catch(Exception e){
				Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();				
			}
        	break;
        
        case MENU_EXIT:
        	closeApp();
        	break;
        }
        return super.onOptionsItemSelected(item);
    }
	
    
  	public boolean checkip(){
    	
    	// Check availability
        HttpClient httpClient = new DefaultHttpClient();
        try {
			HttpGet request = new HttpGet(ip+"/webserv/SAMPLES/READ.XML");
			HttpParams httpParameters = new BasicHttpParams();
			int timeoutConnection = 200;
			HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
			HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection);
			((AbstractHttpClient) httpClient).setParams(httpParameters);
			HttpResponse response = httpClient.execute(request);
		}catch (Exception e) {
			Log.v(LOG_TAG, getString(R.string.IpAddress_name)+ip);
			Log.v(LOG_TAG, getString(R.string.Error2_name)+e.toString());
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(getString(R.string.Error3_name))
		       	.setCancelable(false)
		       	.setPositiveButton(getString(R.string.app_close), new DialogInterface.OnClickListener() {
		         public void onClick(DialogInterface dialog, int id) {
		                WagoAppActivity .this.finish();
		           }
		       })
		       .setNegativeButton(getString(R.string.app_settings), new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   
		        	   // old stuff
		        	   //showAddDialog();
		               //dialog.cancel();
		        	   
		        	   try {
		        		   Intent i = new Intent();
		        		   i.setClass(WagoAppActivity.this, settings_project.class);
		        		   i.putExtra("ip", ip);
		        		   i.putExtra("en_sim", ""+en_sim);
		        		   startActivityForResult(i,2);
						
					   } catch (Exception e) {
					    	Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();				
					   }
		               
		           }
		       });
			AlertDialog alert = builder.create();
			alert.show();
			return false;
		}
		return true;
    }
   
  	protected void onStop(){
        super.onStop();
        saveSettings();
    }
  	
	class SynchTask extends AsyncTask<Void, String, Void> {
			@Override
			protected Void doInBackground(Void... unused) {
				while(true){
					try {
						callStatus();
					} catch (IOException e) {
						e.printStackTrace();
					}
					publishProgress();
					SystemClock.sleep(100);
				}
			}

			public void execute() {
				
			}

			@Override
			protected void onProgressUpdate(String... item) {
				selector(); // Buttons activate
			}

			@Override
			protected void onPostExecute(Void unused) {
				// End should never be reached except app is closed
			}
		}
		
	private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			try{
				int byteadresse=0;
				while(position > 7){
					byteadresse++;
					position-=8;
				}
				try{
					if (!en_sim) {
						URL page = new URL(ip+"/WRITEPI?ADR1=MX"+byteadresse+"."+position+"&VALUE1=1&FORMAT1=%d");
						page.getContent();	
					}
					
				}catch (Exception e){
					System.out.println (e.getMessage());
					Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
				}
				if (!en_sim)
					selector();	
			}catch (Exception e){
				System.out.println (e.getMessage());
				Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
			}
			
		}
	};
	
	private void selector() {
				try{ 
					for (int i = 0; i < ListINPUT.length ; i++) {
						 if(ArrayInputs[i]==1){
							 ListeInput.setItemChecked(i, true);
						 }else{
							 ListeInput.setItemChecked(i, false);
						 }
					}
					for (int i = 0; i < ListOUTPUT.length ; i++) {
						 if(ArrayOutputs[i]==1){
							 ListeOutput.setItemChecked(i, true);
						 }else{
							 ListeOutput.setItemChecked(i, false);
						 }
					}
				}catch (Exception e) {
					Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
				}
				 
				 textview_Merker1.setText(Integer.toString(ArrayMerker[0]));
				 textview_Merker2.setText(Integer.toString(ArrayMerker[1]));
				 textview_Merker3.setText(Integer.toString(ArrayMerker[2]));
		}
	
	
	
	public void callStatus() throws IOException{
		StringBuffer sb = new StringBuffer();
		
		try{
			URL page = new URL(ip+"/webserv/SAMPLES/READ.XML");
			BufferedReader rd = new BufferedReader(new InputStreamReader(page.openStream()));
			String line="";
			while ((line = rd.readLine()) != null) {
				sb.append(line);
			}
		}catch (SocketException e){
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(getString(R.string.Error3_name))
	       	.setCancelable(false).setPositiveButton(getString(R.string.app_yes), new DialogInterface.OnClickListener() {
		       	
				 public void onClick(DialogInterface dialog, int id) {
					 WagoAppActivity .this.finish();
				 }
	       	}).setNegativeButton(getString(R.string.app_no), new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		    });
			AlertDialog alert = builder.create();
            alert.show();
            return;
        }
        ArrayInputs=getStatus(sb.toString(),"<Eingaenge>","</Eingaenge>");
        ArrayOutputs=getStatus(sb.toString(),"<Ausgaenge>","</Ausgaenge>");
        ArrayMerker=getStatus(sb.toString(),"<Merker>","</Merker>");
     }
             
	public int[] getStatus(String s, String startTag, String endTag){
		int start = s.indexOf(startTag)+startTag.length();
		int end = s.indexOf(endTag);
		s = s.substring(start,end);
		int[] arrayint = new int[maxAnzahlIO];
		int item=0;
		StringBuffer temp = new StringBuffer();
		for(int i=0;i < s.length();i++){
			Log.v(LOG_TAG, "i value"+i);
			if (s.charAt(i)!=','){
				temp.append(s.charAt(i));
			}else{
				arrayint[item] =Integer.parseInt(temp.toString());
				item++;
				temp.delete(0, temp.length());
				Log.v(LOG_TAG, "i value"+i);	
			}
			if (i == (s.length()-1)){
				arrayint[item] =Integer.parseInt(temp.toString());
			}	
		}
		return arrayint;
	}
			
	private void showAddDialog() {

	    final String TAG = "test";
	    final Dialog IP_Dialog = new Dialog(this);
	    IP_Dialog.getWindow().setFlags(
	    WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
	    WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
	    IP_Dialog.setTitle("IP Adresse");
	
	    LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	    View dialogView = li.inflate(R.layout.preference, null);
	    IP_Dialog.setContentView(dialogView);
	
	    IP_Dialog.show();
	
	    Button addButton = (Button) dialogView.findViewById(R.id.add_button);
	    Button cancelButton = (Button) dialogView.findViewById(R.id.cancel_button);
	    final EditText ipEditText = (EditText) dialogView.findViewById(R.id.editText_IP);
	
	    addButton.setOnClickListener(new OnClickListener() {
		    // @Override
		    public void onClick(View v) {
			    ip="http://"+ipEditText.getText().toString();
			    if(ip.length()<9){
				    Toast.makeText(getBaseContext(), "Bitte IP Adresse eingeben",
				    Toast.LENGTH_LONG).show();
			    }
			    else{
		            IP_Dialog.dismiss();
			    }
		    }
	    });
	
	    cancelButton.setOnClickListener(new OnClickListener() {
		    // @Override
		    public void onClick(View v) {
	            IP_Dialog.dismiss();
	            WagoAppActivity .this.finish();
		    }
	    });
    }

	private void changeLanguage(){
		// change the locale tag on the device
		Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
        Toast.makeText(this, getString(R.string.app_settings_active_after_restart), Toast.LENGTH_LONG).show();
    }

	private void closeApp() {
				WagoAppActivity .this.finish();
			}

	public void loadSettings(){
				// Load settings from device
		        try{
		        	SharedPreferences settings = getSharedPreferences("PREFS_WAGOAPP", 0);
		        	String S_IP= settings.getString("ip",ip);
		        	boolean S_EnSim= settings.getBoolean("en_sim",en_sim);
		        	ip=S_IP;
		        	en_sim= S_EnSim;		        	
		        }catch (Exception e) {
		        	Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).show();
		        }
			}
	
	public void saveSettings(){
		//SharedPreferences settings = getSharedPreferences("PREFS_WAGOAPP", 0);
		//SharedPreferences.Editor editor = settings.edit();
		//editor.putString("ip", ip);
		//editor.putBoolean("en_sim", en_sim);
		//Toast.makeText(getBaseContext(),"->ip= "+ip,Toast.LENGTH_SHORT).show();
		//Toast.makeText(getBaseContext(),"->sim= "+en_sim,Toast.LENGTH_SHORT).show();
		// Commit the edits!
		//editor.commit();
	}

}